const api = require('../../config/api.js');
const app = getApp();
let that;
// 缓存时间
let expire = 7200; 
/* 限制重复请求 allowRequest（修复快速切换分类，商品错乱的bug）
 * -1	初始值，请求从未发起过  允许
 * 0	正在请求中  不允许
 * 1	请求完成  允许
 */
let allowRequest;
Page({
  data: {
    RootUrl: api.RootUrl,
    ImgRootUrl: app.globalData.ImgRootUrl,
    navList: [],
    goodsList: [],
    parentId:0,
    id: 0,
    currentCategory: {},
    scrollLeft: 0,
    scrollTop: 0,
    scrollHeight: 0,
    page: 1,
    size: 40,
    tips:'正在加载…',
    isLoading:false,
    isHideLoadMore:false,
    goodsId: 0,  //组件api
    fingerEvent: null,  //组件api
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    that = this;
    // 限制重复请求（修复快速切换分类，商品错乱的bug）
    allowRequest = -1;

    if (options.id) {
      if (options.parentId){
        that.setData({
          id: parseInt(options.id),
          parentId: parseInt(options.parentId)
        });
      }else{
        that.setData({
          id: parseInt(options.id)
        });
      }
    }
    
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          scrollHeight: res.windowHeight
        });
      }
    });

    this.getCategoryInfo();
  },
  onReady: function () {
    // 页面渲染完成
  },
  onShow: function () {
    // 页面显示
    // 请求接口，获取购物车列表
    app.cart.CartGoodsCount().then(function (res) {
      app.globalData.cartList = res.data.cartList;
    }).catch((err) => {
      console.log(err)
    });
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  },
  onShareAppMessage: function () {
    return {
      title: app.globalData.title + '-' + that.data.currentCategory.name,
      desc: that.data.currentCategory.descript,
      path: '/pages/category/category?id=' + this.data.id
    }
  },
  // 获取分类
  getCategoryInfo: function () {
    // 来源：分类页（this.data.parentId是分类页传来的，其他页面无此参数）
    let cacheKey = 'Category' + this.data.parentId;
    // 读取缓存（缓存是在分类页设置的）
    let CategoryInfo = app.cache.get(cacheKey);
    if (CategoryInfo){
      that.setData({
        navList: CategoryInfo.subCategoryList
      });
      that.getGoodsList();
    }else{
      app.util.get(api.GoodsCategory, { id: this.data.id }).then(function (res) {
        if (res.errno == 0) {
          that.data.parentId = res.data.parentCategory.id
          that.setData({
            navList: res.data.brotherCategory
          });
          that.getGoodsList();
        } else {
          //显示错误信息
          app.util.showToast('获取分类失败');
        }
      });
    }
  },
  // nav位置
  setNav: function(){
    let currentIndex = 0;
    let navListCount = that.data.navList.length;
    for (let i = 0; i < navListCount; i++) {
      currentIndex += 1;
      if (that.data.navList[i].id == that.data.id) {
        break;
      }
    }
    if (currentIndex > navListCount / 2 && navListCount > 5) {
      that.setData({
        scrollLeft: currentIndex * 60
      });
    }
  },
  // 获取当前分类商品
  getGoodsList: function () {
    that.setNav();
    let page = this.data.page;
    app.util.get(api.GoodsList, {categoryId: that.data.id, page: page, size: that.data.size}).then(function (res) {
      if (res.data.count != 0) {
        let goodsList = res.data.goodsList;
        that.data.page = res.data.currentPage;
        that.setData({
          currentCategory: res.data.currentCategory,
          isHideLoadMore: true
        });
        //商品数量 [对应购物车]
        that.setGoodsCount(goodsList);
      } else {
        that.data.page = page - 1;
        that.setData({
          currentCategory: res.data.currentCategory,
          tips: '没有更多了',
          isLoading: true,
          isHideLoadMore: false
        });
        // 请求完成
        allowRequest = 1;
      }
    });
  },
  // 切换分类
  switchCate: function (event) {
    if (this.data.id == event.currentTarget.dataset.id) {
      return false;
    }

    // 限制重复请求
    if (allowRequest === 0) {
      return;
    }
    // 正在请求中
    allowRequest = 0;

    // 保存当前页面数据到缓存
    let cacheKey = 'currentCategoryInfo' + that.data.id;
    let data = {
      id: that.data.id,
      goodsList: that.data.goodsList,
      currentCategory: that.data.currentCategory,
      page: that.data.page
    };
    app.cache.set(cacheKey, data, 600);

    // 设置导航偏移量
    var clientX = event.detail.x;
    var currentTarget = event.currentTarget;
    if (clientX < 60) {
      that.setData({
        scrollLeft: currentTarget.offsetLeft - 60
      });
    } else if (clientX > 330) {
      that.setData({
        scrollLeft: currentTarget.offsetLeft
      });
    }

    // 即将加载页的缓存key
    cacheKey = 'currentCategoryInfo' + event.currentTarget.dataset.id;
    // 读取缓存
    let currentCategoryInfo = app.cache.get(cacheKey);
    if (currentCategoryInfo){
      this.setData({
        id: currentCategoryInfo.id,
        goodsList: [],
        currentCategory: currentCategoryInfo.currentCategory,
        page: currentCategoryInfo.page
      });
      //商品数量 [对应购物车]
      that.setGoodsCount(currentCategoryInfo.goodsList);
      return;
    }
    
    // 加载新页面数据
    this.setData({
      id: event.currentTarget.dataset.id,
      goodsList:[],
      page:1,
      tips: '正在加载…',
      isHideLoadMore: false,
      isLoading: false
    });
    that.getGoodsList();
  },
  //上拉触底函数，加载更多
  onReachBottom: function() {
    // 限制重复请求
    if (allowRequest === 0) {
      return;
    }
    // 正在请求中
    allowRequest = 0;
    
    this.setData({
      page: this.data.page + 1,
      isHideLoadMore: false,   //显示正在加载
    });
    that.getGoodsList();
  },
  //设置商品数量 [对应购物车数量]
  setGoodsCount: function (goodsList) {
    let goods = app.globalData.cartList.goods;
    let _goodsList = goodsList.map(function (v) {
      if (v.spec_array == '') {
        //goods
        v.count = goods[v.id] ? parseInt(goods[v.id].count) : 0;
      } else {
        //product
        v.count = 0;
      }
      return v;
    });
    that.setData({
      goodsList: that.data.goodsList.concat(_goodsList)
    });
    // 请求完成
    allowRequest = 1;
  },
  //减
  cutNumber: function (event) {
    let i = event.currentTarget.dataset.i;  //当前分类的商品列表索引
    let type = event.currentTarget.dataset.type;  //类型：商品goods，货品product
    let goods_id = event.currentTarget.id;  //商品id
    let product_id = 0; //默认货品id
    let _goodsList = that.data.goodsList;
    if (type != 'goods') {
      //货品
      that.setData({
        goodsId: goods_id,
      });
    } else {
      //商品
      switch (_goodsList[i].count) {
        case 0:
          return false;
          break;
        case 1:
          app.cart.CartDelete(goods_id + '_' + product_id).then(function (res) {
            app.globalData.cartGoodsCount = res.data.cartTotal.goodsCount;
            that.setCartListGoods(goods_id,0);

            that.setData({
              ["goodsList[" + i + "].count"]: 0
            });
          }).catch((err) => {

          });
          break;
        default:
          app.cart.CartAdd(goods_id, product_id, -1).then(function (res) {
            let count = _goodsList[i].count - 1;
            app.globalData.cartGoodsCount = res.data.cartTotal.goodsCount;
            that.setCartListGoods(goods_id, count);

            that.setData({
              ["goodsList[" + i + "].count"]: count
            });
          }).catch((err) => {

          });
          break;
      }
    }
  },
  //加
  addNumber: function (event) {
    console.log(event)
    that.setData({
      fingerEvent: event
    })
    let i = event.currentTarget.dataset.i;  //当前分类的商品列表索引
    let type = event.currentTarget.dataset.type;  //类型：商品goods，货品product
    let goods_id = event.currentTarget.id;  //商品id    
    let product_id = 0; //默认货品id
    let _goodsList = that.data.goodsList;
    if (type != 'goods') {
      //货品
    } else {
      app.cart.CartAdd(goods_id, product_id, 1).then(function (res) {
        //成功
        let count = _goodsList[i].count + 1;
        app.globalData.cartGoodsCount = res.data.cartTotal.goodsCount;
        

        that.setData({
          ["goodsList[" + i + "].count"]: count
        });
        that.setCartListGoods(goods_id, count);
      }).catch((err) => {
        //失败        
      });
    }
  },
  // 修改购物车商品的数量（减少网络请求，保证本地数据与服务器一致）
  setCartListGoods: function (goods_id, count = 0){
    let goods = app.globalData.cartList.goods;
    //console.log(app.globalData.cartList.goods)
    if ( goods[goods_id] ){
      goods[goods_id].count = parseInt(count);
    }else{
      goods[goods_id] = { count: parseInt(count) };
    }
    app.globalData.cartList.goods = goods;
    //console.log(goods)
  },
})